package encaps.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class GenreManager {

    private Connection conn = null;
    private DataSource dataSource;
    private PreparedStatement ps;
    private HashSet availableGenres;

    public GenreManager() throws NamingException {
        dataSource = DatabaseUtil.getDataSource();
        try {
            conn = dataSource.getConnection();
            ps = conn.prepareStatement("SELECT * FROM genre");
            ResultSet rs = ps.executeQuery();
            availableGenres = new HashSet();
            while (rs.next()) {
                availableGenres.add(rs.getString(1));
            }
        } catch (SQLException ex) {
        } finally {
            DatabaseUtil.closeConnection(conn, ps);
        }
    }

    public Set getAvailableGenres() {
        return (Set) availableGenres;
    }

    public void createGenre(String name) throws SQLException {
        try {
            conn = dataSource.getConnection();
            ps = conn.prepareStatement("INSERT INTO genre(name) VALUES(?)");
            ps.setString(1, name);
            if (ps.executeUpdate() != 1) {
                throw new SQLException("Insertion error");
            }
            availableGenres.add(name);
        } finally {
            DatabaseUtil.closeConnection(conn, ps);
        }
    }

    public void deleteGenre(String name) throws SQLException {
        try {
            conn = dataSource.getConnection();
            ps = conn.prepareStatement("DELETE FROM genre WHERE name=?");
            ps.setString(1, name);
            if (ps.executeUpdate() != 1) {
                throw new SQLException("Delete error");
            }
            availableGenres.remove(name);
        } finally {
            DatabaseUtil.closeConnection(conn, ps);
        }
    }
}
